//
//  PlayMusicViewController.m
//  悦享
//
//  Created by dllo on 16/3/21.
//  Copyright © 2016年 张洪国. All rights reserved.
//

#import "PlayMusicViewController.h"
#import <UIImageView+WebCache.h>
#import <AVFoundation/AVFoundation.h>
#import <CoreGraphics/CoreGraphics.h>
#import "MyMusicInformation.h"
#import "PlayMusicHelp.h"
#import "SongsModel.h"
#import "LSPaoMaView.h"

@interface PlayMusicViewController ()

@property (nonatomic, assign) BOOL isPlay;
/// 播放图片
@property (nonatomic, retain) UIImageView *imgView;
/// 底层大的图片
@property (nonatomic, retain) UIImageView *bigImg;
/// 毛玻璃
@property (nonatomic , strong) UIVisualEffectView *visualEfView;
/// 播放进度slider
@property (nonatomic, retain) UISlider *playProgress;
/// 初始时间
@property (nonatomic, retain) UILabel *initialLabel;
/// 总时间
@property (nonatomic, retain) UILabel *totalLabel;
/// 播放按钮
@property (nonatomic, retain) UIImageView *playImg;
/// 上一曲
@property (nonatomic, retain) UIButton *upButton;
/// 下一曲
@property (nonatomic, retain) UIButton *downButton;
/// 歌曲名字(跑马灯形式)
@property (nonatomic, retain) LSPaoMaView *paoMaView;

@property (nonatomic, retain) UIView *headerView;

@end

@implementation PlayMusicViewController

- (void)viewWillAppear:(BOOL)animated {
    
    [self performSelector:@selector(startAnimate) withObject:self afterDelay:0.1];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    
    
//    [self performSelector:@selector(startAnimate) withObject:self afterDelay:0.1];
    
    [self createImgView];
    [self createPlayView];
    [self playSongs];
    
    // 返回按钮
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(20, 20, 32, 32);
    [self.view addSubview:button];
    [button setBackgroundImage:[[UIImage imageNamed:@"iconfont-linedown.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:(UIControlStateNormal)];

    [button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
    
}

// 创建播放页面的背景图
- (void)createImgView {
    
    // 背景大的图片
    self.bigImg = [[UIImageView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    [self.bigImg sd_setImageWithURL:[NSURL URLWithString:_imgViewUrl] placeholderImage:[UIImage imageNamed:PLACE_HLODER]];
    [self.view addSubview:_bigImg];
    
    // 毛玻璃
    self.visualEfView = [[UIVisualEffectView alloc] initWithEffect:[UIBlurEffect effectWithStyle:UIBlurEffectStyleLight]];
    _visualEfView.frame = CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height);
    _visualEfView.alpha = 1.0;
    [self.bigImg addSubview:_visualEfView];
    
    
   self.headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SREEN_WIDTH, 80)];
    _headerView.backgroundColor = [UIColor grayColor];
    _headerView.alpha = 0.5;
    [self.bigImg addSubview:_headerView];
    
    
    [self paoView:_nameString];
    
                          

   
    // 专辑图片
    self.imgView = [[UIImageView alloc] initWithFrame:CGRectMake(20, 120, SREEN_WIDTH - 40, SREEN_WIDTH - 40)];
    [self.imgView sd_setImageWithURL:[NSURL URLWithString:_imgViewUrl] placeholderImage:[UIImage imageNamed:PLACE_HLODER]];
    // 设置圆角
    self.imgView.layer.cornerRadius = (SREEN_WIDTH - 40) / 2.0;
    // 裁掉边框
    self.imgView.layer.masksToBounds = YES;
    // 加边框
    self.imgView.layer.borderWidth = 5;
    self.imgView.layer.borderColor = [UIColor cyanColor].CGColor;
    
    [self.view addSubview:_imgView];
    
    [self performSelector:@selector(startAnimate) withObject:self afterDelay:0.1];
    
    _visualEfView.userInteractionEnabled = YES;
    
    _isPlay = YES;

    
}

- (void)paoView:(NSString *)name {
    // 歌名跑马灯
    NSLog(@"%@", name);
    
    CGSize size = [APPTools labelRectWithSize:CGSizeMake(SREEN_WIDTH, 40) LabelText:name Font:[UIFont systemFontOfSize:17]];
    UIColor *color = [UIColor whiteColor];
    
    self.paoMaView = [[LSPaoMaView alloc] initWithFrame:CGRectMake(0, 0, size.width, 40) title:name BackColor:nil textColor:color textFont:17];
    _paoMaView.center = _headerView.center;
    [_headerView addSubview:_paoMaView];
    
}

// 原型专辑图片旋转动画
- (void)startAnimate {
    
    // CAlayer动画
    // Core Animation
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    // 旋转的起始值
    animation.fromValue = [NSNumber numberWithFloat:0];
    // 旋转的结束值
    // π 是180°  2π是360°
    animation.toValue = [NSNumber numberWithFloat:M_PI];
    // 重复次数
    animation.repeatCount = NSIntegerMax;
    // 时间
    animation.duration = 5;
    // 是否自动回到原来的位置
    //    animation.autoreverses = YES;
    // 是否按照结束位置继续旋转
    animation.cumulative = YES;
    [self.imgView.layer addAnimation:animation forKey:@"标记"];
    
    
}

#pragma mark - 控制歌曲播放
- (void)playSongs {
    
    //播放
    [CY_sharePlayeMusicHelp playMusicMp3Url:_musicUrl];
    //   // 0.1秒回调
    CY_sharePlayeMusicHelp.playTimerBlock = ^(CGFloat timer){
        
        //播放时间
    self.initialLabel.text = [self timeToString:timer]; //调用方法，赋值
        //总时间
    self.totalLabel.text = [self timeToString:CY_sharePlayeMusicHelp.sumtime - timer];
    [self playTimer:timer]; //调用方法
        
    };
    _playImg.image = [UIImage imageNamed:@"bofang.png"];

    CY_sharePlayeMusicHelp.playToEndBlock = ^(){
        NSLog(@"播放完我单例的观察者会观察到 就会调用block 走这个方法, 播放完在这里做你想做的");
    // 当歌曲播放完毕, 自动跳到下一曲
    if (_index == _playArr.count - 1) {
            _index = 0;
            SongsModel *model = _playArr[_index];
            AuditionListModel *listModel = model.auditionListArr[0];
            [CY_sharePlayeMusicHelp playMusicMp3Url:listModel.url];
            [self.imgView sd_setImageWithURL:[NSURL URLWithString:model.picUrl] placeholderImage:[UIImage imageNamed:PLACE_HLODER]];
            [_paoMaView setHidden:YES];
            [self paoView:model.name];
            _index++;
            
        }
    else if (_index < _playArr.count) {
            
            _index++;
            SongsModel *model = _playArr[_index];
            AuditionListModel *listModel = model.auditionListArr[0];
            [CY_sharePlayeMusicHelp playMusicMp3Url:listModel.url];
            [self.imgView sd_setImageWithURL:[NSURL URLWithString:model.picUrl] placeholderImage:[UIImage imageNamed:PLACE_HLODER]];
            [_paoMaView setHidden:YES];
            [self paoView:model.name];
        }

        
    // 暂停
    CFTimeInterval stopTime = [self.imgView.layer convertTime:CACurrentMediaTime() fromLayer:nil];
    // 设置动画速度
    self.imgView.layer.speed = 0;
    // 保存时间的偏移量
    self.imgView.layer.timeOffset = stopTime;
    _playImg.image = [UIImage imageNamed:@"bofang.png"];

    };
    
}

#pragma mark - 播放界面布局
- (void)createPlayView {
    
    UIView *bigView = [[UIView alloc] initWithFrame:CGRectMake(0, SREEN_HEIGHT - 50, SREEN_WIDTH, 50)];
    bigView.backgroundColor = [UIColor colorWithRed:0.13 green:0.13 blue:0.13 alpha:0.8];
    [self.view addSubview:bigView];
    
    // 初始时间
    self.initialLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, SREEN_HEIGHT - 100, 50, 30)];
    self.initialLabel.text = @"--:--";
    self.initialLabel.textAlignment = NSTextAlignmentCenter;
    self.initialLabel.textColor = [UIColor whiteColor];
    [self.view addSubview:_initialLabel];

    // 总时间
    self.totalLabel = [[UILabel alloc] initWithFrame:CGRectMake(SREEN_WIDTH - 50, SREEN_HEIGHT - 100, 50, 30)];
    self.totalLabel.text = @"--:--";
    self.totalLabel.textAlignment = NSTextAlignmentCenter;
    self.totalLabel.textColor = [UIColor whiteColor];
    [self.view addSubview:_totalLabel];
    
    // 时间进度slider
    self.playProgress = [[UISlider alloc] initWithFrame:CGRectMake(self.initialLabel.frame.size.width, SREEN_HEIGHT - 100, SREEN_WIDTH - 100, 30)];
    [self.view addSubview:_playProgress];
    [_playProgress addTarget:self action:@selector(sliderAction:) forControlEvents:UIControlEventValueChanged];
    
    // 控制播放暂停的开关
    self.playImg = [[UIImageView alloc] initWithFrame:CGRectMake(SREEN_WIDTH / 2 - 20, 5, 40, 40)];
    _playImg.image = [UIImage imageNamed:@"zanting.png"];
    [bigView addSubview:_playImg];

    
    // 给imgView添加手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
    [self.playImg addGestureRecognizer:tap];
    _playImg.userInteractionEnabled = YES;

    
    self.upButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _upButton.frame = CGRectMake(self.playImg.frame.origin.x - 70, 5, 40, 40);
    [_upButton setBackgroundImage:[UIImage imageNamed:@"iconfont-icon1.png"] forState:(UIControlStateNormal)];
    [bigView addSubview:_upButton];
    [_upButton addTarget:self action:@selector(upAction:) forControlEvents:(UIControlEventTouchUpInside)];
    
    
    self.downButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _downButton.frame = CGRectMake(self.playImg.frame.origin.x + 70, 5, 40, 40);
    [_downButton setBackgroundImage:[UIImage imageNamed:@"iconfont-icon2.png"] forState:(UIControlStateNormal)];
    [bigView addSubview:_downButton];
    [_downButton addTarget:self action:@selector(downAction:) forControlEvents:(UIControlEventTouchUpInside)];
    
}

#pragma mark - 控制暂停和开始
- (void)tapAction:(UITapGestureRecognizer *)tap {

    
    if (_isPlay == YES) {
        // 暂停
        CFTimeInterval stopTime = [self.imgView.layer convertTime:CACurrentMediaTime() fromLayer:nil];
        // 设置动画速度
        self.imgView.layer.speed = 0;
        // 保存时间的偏移量
        self.imgView.layer.timeOffset = stopTime;
        _playImg.image = [UIImage imageNamed:@"zanting.png"];
        [CY_sharePlayeMusicHelp pause];
        
    } else {
        // 继续
        // 找到时间偏移量
        CFTimeInterval stopTime = self.imgView.layer.timeOffset;
        // 速度设置为1
        self.imgView.layer.speed = 1;
        // beginTime 重置
        self.imgView.layer.beginTime = 0;
        self.imgView.layer.timeOffset = 0;
        // 设置开始的时间
        self.imgView.layer.beginTime = [self.imgView.layer convertTime:CACurrentMediaTime() fromLayer:nil] - stopTime;
        _playImg.image = [UIImage imageNamed:@"bofang.png"];
        
        [CY_sharePlayeMusicHelp seekToTime:_playProgress.value];
        
    }
    
    // 状态反转
    _isPlay = !_isPlay;
    
}

#pragma mark - 上一曲
- (void)upAction:(UIButton *)button {

    
    NSInteger count = _index;
    count++;
    NSLog(@"%ld", (long)count);


   
    _index--;
    if (_index < 0) {
        _index = _playArr.count - 1;
        SongsModel *model = _playArr[_index];
    
        AuditionListModel *listModel = model.auditionListArr[0];
        [CY_sharePlayeMusicHelp playMusicMp3Url:listModel.url];
        [self.imgView sd_setImageWithURL:[NSURL URLWithString:model.picUrl] placeholderImage:[UIImage imageNamed:PLACE_HLODER]];
        
        [_paoMaView setHidden:YES];
        [self paoView:model.name];
    
        NSLog(@"%ld", _index);
    }else {
        
        SongsModel *model = _playArr[_index];
        AuditionListModel *listModel = model.auditionListArr[0];
        [CY_sharePlayeMusicHelp playMusicMp3Url:listModel.url];
        [self.imgView sd_setImageWithURL:[NSURL URLWithString:model.picUrl] placeholderImage:[UIImage imageNamed:PLACE_HLODER]];
        [_paoMaView setHidden:YES];
        [self paoView:model.name];
    }

    
}

#pragma mark - 下一曲
- (void)downAction:(UIButton *)button {
    
    if (_index == _playArr.count - 1) {
        _index = 0;
        SongsModel *model = _playArr[_index];
        _nameString = model.name;
        AuditionListModel *listModel = model.auditionListArr[0];
        [CY_sharePlayeMusicHelp playMusicMp3Url:listModel.url];
        [self.imgView sd_setImageWithURL:[NSURL URLWithString:model.picUrl] placeholderImage:[UIImage imageNamed:PLACE_HLODER]];
        [_paoMaView setHidden:YES];
        [self paoView:model.name];
        _index++;
        
    }
    else if (_index < _playArr.count) {

        _index++;
        SongsModel *model = _playArr[_index];
        _nameString = model.name;
        AuditionListModel *listModel = model.auditionListArr[0];
        [CY_sharePlayeMusicHelp playMusicMp3Url:listModel.url];
        [self.imgView sd_setImageWithURL:[NSURL URLWithString:model.picUrl] placeholderImage:[UIImage imageNamed:PLACE_HLODER]];
        [_paoMaView setHidden:YES];
        [self paoView:model.name];
    }
    
}

#pragma mark - 0.1秒block回调的方法
- (void)playTimer:(CGFloat)timer{
    
    // 暂停
    CFTimeInterval stopTime = [self.imgView.layer convertTime:CACurrentMediaTime() fromLayer:nil];
    // 设置动画速度
    self.imgView.layer.speed = 0;
    // 保存时间的偏移量
    self.imgView.layer.timeOffset = stopTime;
    self.playProgress.value = timer / CY_sharePlayeMusicHelp.sumtime; //给滑竿赋值
    
    // 找到时间偏移量
    CFTimeInterval stopTime1 = self.imgView.layer.timeOffset;
    // 速度设置为1
    self.imgView.layer.speed = 1;
    // beginTime 重置
    self.imgView.layer.beginTime = 0;
    self.imgView.layer.timeOffset = 0;
    // 设置开始的时间
    self.imgView.layer.beginTime = [self.imgView.layer convertTime:CACurrentMediaTime() fromLayer:nil] - stopTime1;

    
    
}

#pragma mark - 控制播放进度
- (void)sliderAction:(UISlider *)slider {
    
    
    [CY_sharePlayeMusicHelp seekToTime:slider.value];
    
    
}

#pragma mark - 获取字符串时间
- (NSString *)timeToString:(CGFloat)time{
    
    NSInteger minutes = (NSInteger)time / 60; //分钟
    NSInteger seconds = (NSInteger)time % 60; //秒
    //转换为string
    NSString *string = [NSString stringWithFormat:@"%02ld:%02ld",(long)minutes,seconds];
    
    return string;
}

#pragma mark - 返回按钮点击方法
- (void)buttonAction:(UIButton *)button {
    
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
    
    // 返回上一界面 歌曲停止
//    [CY_sharePlayeMusicHelp pause];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
